<template>
  <div class="task-manage">
    <!-- 搜索栏 -->
    <el-form :model="searchParm" :inline="true" size="default">
      <el-form-item>
        <el-input placeholder="请输入课程名" v-model="searchParm.username" />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" @click="searchBtn">查询</el-button>
        <el-button icon="Close" type="danger" plain @click="resetBtn"
          >重置</el-button
        >
        <el-button icon="Plus" type="primary" @click="onOpenCreateTaskDialog"
          >新增课程</el-button
        >
      </el-form-item>
    </el-form>
    <el-table :data="tasks" style="width: 100%">
      <el-table-column
        prop="taskName"
        label="课程名"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="taskDescription"
        label="课程介绍"
      ></el-table-column>
      <el-table-column prop="dueDate" label="截止日期" width="280">
        <template #default="{ row }">
          {{ row.dueDate ? row.dueDate.toLocaleString() : '' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="onEditTask(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteTask(row.taskId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="currentTask" :rules="rules" ref="taskForm">
        <el-form-item label="课程名" prop="taskName">
          <el-input v-model="currentTask.taskName"></el-input>
        </el-form-item>
        <el-form-item label="课程介绍" prop="taskDescription">
          <el-input
            v-model="currentTask.taskDescription"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="截止日期" prop="dueDate">
          <el-date-picker
            v-model="currentTask.dueDate"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            currentTask.id !== null && currentTask.id !== undefined
              ? updateTask()
              : createNewTask()
          "
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as taskApi from '@/api/task.js'
import useUserInfoStore from '@/stores/userInfo.js'

const store = useUserInfoStore()
const searchParm = reactive({ username: '' })
const tasks = ref([])
const currentTask = reactive({
  taskName: '',
  taskDescription: '',
  dueDate: null,
  id: null,
  teacherId: null
})
const dialogVisible = ref(false)
const dialogTitle = ref('添加课程')
const taskForm = ref(null)

// 表单验证规则
const rules = reactive({
  taskName: [
    { required: true, message: '请输入课程名', trigger: 'blur' },
    { min: 3, max: 20, message: '课程名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  taskDescription: [
    { required: true, message: '请输入课程介绍', trigger: 'blur' },
    { max: 1000, message: '课程介绍不能超过1000个字符', trigger: 'blur' }
  ],
  dueDate: [
    { required: true, message: '请选择截止日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        const today = new Date()
        today.setHours(0, 0, 0, 0)
        if (value) {
          const date = new Date(value)
          if (date < today) {
            callback(new Error('截止日期不能小于当天'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

const fetchTasks = async () => {
  try {
    const response = await taskApi.getTeacherTasks(store.info.id)
    tasks.value = response.data
    // 确保 dueDate 被正确解析为 Date 对象
    tasks.value.forEach(task => {
      let parsedDate
      if (Array.isArray(task.dueDate)) {
        // 处理数组格式的日期
        parsedDate = new Date(
          task.dueDate[0],
          task.dueDate[1] - 1,
          task.dueDate[2],
          task.dueDate[3],
          task.dueDate[4],
          task.dueDate[5] || 0
        )
      } else {
        parsedDate = new Date(task.dueDate)
      }
      if (isNaN(parsedDate.getTime())) {
        task.dueDate = null
      } else {
        task.dueDate = parsedDate
      }
    })
  } catch {
    ElMessage.error('获取课程列表失败')
  }
}

// 更新任务的函数
const updateTask = async () => {
  try {
    await taskForm.value.validate()
    let taskToSend = {
      ...currentTask,
      dueDate: currentTask.dueDate
        ? convertLocalToUTC(new Date(currentTask.dueDate)).toISOString()
        : null,
      updatedAt: new Date().toISOString() // 更新时间设置为当前时间
    }
    if (currentTask.id !== null && currentTask.id !== undefined) {
      // 调用 updateTaskById 函数进行更新
      await taskApi.updateTaskById(currentTask.id, taskToSend)
      await fetchTasks() // 重新获取任务列表
      dialogVisible.value = false // 关闭对话框
      ElMessage.success('编辑课程成功')
    }
  } catch {
    ElMessage.error('格式不符合规范')
  }
}

// 创建新任务的函数
const createNewTask = async () => {
  try {
    await taskForm.value.validate()
    let taskToSend = {
      ...currentTask,
      teacherId: store.info.id, // 确保发送请求时包含 teacherid
      // 确保 dueDate 被正确格式化为 ISO 字符串
      dueDate: currentTask.dueDate ? currentTask.dueDate.toISOString() : null,
      upDatedAt: new Date().toISOString() // 更新时间设置为当前时间
    }
    // 删除 id 属性，因为创建新任务时不应包含 id
    delete taskToSend.id
    await taskApi.createTask(taskToSend) // 调用 API 创建新任务
    await fetchTasks() // 重新获取任务列表
    dialogVisible.value = false // 关闭对话框
    ElMessage.success('添加课程成功')
  } catch {
    ElMessage.error('格式不符合规范')
  }
}

// 编辑任务的函数
const onEditTask = task => {
  currentTask.taskName = task.taskName
  currentTask.taskDescription = task.taskDescription
  // 确保日期被正确设置为 Date 对象
  let parsedDate
  if (Array.isArray(task.dueDate)) {
    // 处理数组格式的日期
    parsedDate = new Date(
      task.dueDate[0],
      task.dueDate[1] - 1,
      task.dueDate[2],
      task.dueDate[3],
      task.dueDate[4]
    )
  } else {
    parsedDate = new Date(task.dueDate)
  }
  if (isNaN(parsedDate.getTime())) {
    currentTask.dueDate = null
  } else {
    currentTask.dueDate = parsedDate
  }
  currentTask.id = task.taskId // 使用 taskid 而不是 id
  currentTask.teacherId = task.teacherId // 确保编辑时包含 teacherid
  dialogTitle.value = '编辑课程'
  dialogVisible.value = true
}

// 打开创建任务对话框的函数
const onOpenCreateTaskDialog = () => {
  currentTask.taskName = ''
  currentTask.taskDescription = ''
  currentTask.dueDate = null
  currentTask.id = null // 确保在创建新任务时 id 为 null
  currentTask.teacherId = store.info.id // 确保打开创建对话框时包含 teacherid
  dialogTitle.value = '添加课程'
  dialogVisible.value = true
}

// 删除任务的函数
const deleteTask = async id => {
  try {
    if (id === null || id === undefined) {
      return
    }
    const confirmed = await ElMessageBox.confirm(
      '你确定要删除这个课程吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    if (confirmed) {
      await taskApi.deleteTaskById(id)
      await fetchTasks()
      ElMessage.success('删除课程成功')
    }
  } catch (error) {
    // 如果用户取消了删除操作，error 是一个 Cancel 操作的错误
    if (error !== 'cancel') {
      ElMessage.error('删除课程失败')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}
// 本地时间（CST）转换为UTC时间
const convertLocalToUTC = localDate => {
  const offset = 8 * 60 * 60 * 1000 // CST时区偏移量
  return new Date(localDate.getTime() + offset)
}
fetchTasks()
</script>

<style scoped>
.task-manage {
  margin: 20px;
  display: flex;
  flex-direction: column;
}
</style>
